package com.roubsite.cloud.security.utils;

import com.roubsite.cloud.common.service.RedisService;
import com.roubsite.cloud.common.userinfo.RCUserUtils;
import com.roubsite.cloud.common.userinfo.SecurityUserDetails;
import com.roubsite.cloud.common.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description token 生成工具类
 */
@Slf4j
@Component
public class TokenUtil {
    @Autowired
    RedisService redisService;
    @Autowired
    RCUserUtils rcUserUtils;
    @Value("${token.expired}")
    public int tokenExpired;
    @Value("${token.refresh.expired}")
    int tokenRefreshExpired;


    /**
     * @author Administrator
     * @date 2021/3/9 17:36
     * @description 生成 token
     */
    public String generateToken(SecurityUserDetails claims, String userId) {

        String token = null;
        try {
            token = RSAUtils.encrypt(userId);
            redisService.putRedis("token" + userId, claims, tokenExpired);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return token;
    }

    /**
     * 解密Jwt内容
     *
     * @param token token
     * @return Claims
     */
    public SecurityUserDetails getTokenBody(String token) {
        return rcUserUtils.getUserInfo(token);
    }

    /**
     * @Description: 校验token是否有效
     * @Param: [token]
     * @return: boolean
     * @Author: starao
     * @Date: 2021/11/27
     */
    public String verifyToken(String token) {
        SecurityUserDetails m = getTokenBody(token);
        if (ObjectUtils.isEmpty(m)) {
            return ("token 已过期 ");
        } else {
            return null;
        }

    }

    public boolean refreshToken(String refreshToken) {
        try {
            String uid = RSAUtils.decrypt(refreshToken);
            redisService.delFromRedis("token" + uid);
            SecurityUserDetails map = (SecurityUserDetails) redisService.getFromRedis("refresh" + uid);
            if (ObjectUtils.isNotEmpty(map)) {
                redisService.putRedis("token" + uid, map, tokenExpired);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


    public String generateRefreshToken(SecurityUserDetails claims, String uid) {
        String token = null;
        try {
            token = RSAUtils.encrypt(uid);
            redisService.putRedis("refresh" + uid, claims, tokenRefreshExpired);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return token;
    }
}
